const express = require('express');
const { chatCompletion, textCompletion } = require('../utils/openai-adapter');

const router = express.Router();

/**
 * @route POST /api/openai/chat/completions
 * @desc OpenAI 兼容的聊天补全 API
 */
router.post('/chat/completions', async (req, res, next) => {
  try {
    const response = await chatCompletion(req.body);
    res.json(response);
  } catch (error) {
    next(error);
  }
});

/**
 * @route POST /api/openai/completions
 * @desc OpenAI 兼容的文本补全 API
 */
router.post('/completions', async (req, res, next) => {
  try {
    const response = await textCompletion(req.body);
    res.json(response);
  } catch (error) {
    next(error);
  }
});

/**
 * @route GET /api/openai/models
 * @desc 获取可用模型列表
 */
router.get('/models', (req, res) => {
  // 返回一个与 DashScope 兼容的模型列表
  res.json({
    object: 'list',
    data: [
      {
        id: 'qwen-max',
        object: 'model',
        created: Math.floor(Date.now() / 1000),
        owned_by: 'alibaba-cloud'
      },
      {
        id: 'qwen-plus',
        object: 'model',
        created: Math.floor(Date.now() / 1000),
        owned_by: 'alibaba-cloud'
      },
      {
        id: 'qwen-vl-max',
        object: 'model',
        created: Math.floor(Date.now() / 1000),
        owned_by: 'alibaba-cloud'
      },
      {
        id: 'qwen-vl-plus',
        object: 'model',
        created: Math.floor(Date.now() / 1000),
        owned_by: 'alibaba-cloud'
      },
      {
        id: 'bailian-default', // 兼容我们原来的模型名称
        object: 'model',
        created: Math.floor(Date.now() / 1000),
        owned_by: 'alibaba-cloud'
      }
    ]
  });
});

module.exports = { openaiRouter: router };
